package com.lancoo.klgcourseware.ui.fragment.pronounceTrain;

import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.github.lzyzsd.circleprogress.DonutProgress;
import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.entity.bean.KlgConstant;
import com.lancoo.klgcourseware.entity.bean.SpellCharacterBean;
import com.lancoo.klgcourseware.ui.adapter.FastCharacterAdapter;
import com.lancoo.klgcourseware.ui.adapter.SlowCharacterAdapter;
import com.lancoo.klgcourseware.ui.fragment.basicTrain.BasicTrainBaseFragment;
import com.lancoo.klgcourseware.ui.widget.CountTimeView;
import com.lancoo.klgcourseware.utils.KlgToolUtils;
import com.lancoo.klgcourseware.utils.UniCodeUtils;
import com.stkouyu.entity.LgEvaluateObj;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by pengmi on 2019/8/21 20:40
 * Description:发音训练-朗读训练
 */
public class PronounceReadingTrainFragment extends  PronounceBaseFragment{


    private RecyclerView rv_slow,rv_fast;
    private RelativeLayout rl_slow,rl_fast,rl_recorder,rl_countTime;
    private ImageView img_arrorSlow,img_completeLogo;
    private TextView tv_syllableSlow,tv_syllableFast,tv_alert,tv_giveUpTrain;
    private SlowCharacterAdapter slowCharacterAdapter;
    protected FastCharacterAdapter fastCharacterRyAdapter;
    private final int TOTALTIME_SLOWTRAIN=4000;
    private final int TOTALTIME_FASTTRAIN=3000;
    private int slowTrainIndex,slowReadScore,fastReadScore;

    protected List<SpellCharacterBean> fastCharacterBeans,slowCharacterBeans,slowTimeBeans;
    private DonutProgress donutProgress;
    private boolean haiSlowTrain=true,isQuality;
    private String slowRecordUrl,fastRecordUrl;
    private CountTimeView countTimeView;
    private int totalScore;


    @Override
    protected int getContentViewId() {
        return R.layout.klg_fragment_pronounce_reading_train;
    }

    @Override
    protected void initView(View view) {
        if(wordArticulation==null){
            return;
        }
        splitData();
        rl_slow = view.findViewById(R.id.rl_slow);
        rl_fast = view.findViewById(R.id.rl_fast);
        img_arrorSlow = view.findViewById(R.id.img_arror_slow);
        rv_slow = view.findViewById(R.id.recycler_view_slow);
        rv_fast = view.findViewById(R.id.recycler_view_fast);
        rv_slow.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false));
        rv_fast.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false));
        slowCharacterAdapter = new SlowCharacterAdapter(getContext(),slowCharacterBeans,0);
        fastCharacterRyAdapter = new FastCharacterAdapter(getContext(),fastCharacterBeans);
        rv_slow.setAdapter(slowCharacterAdapter);
        rv_fast.setAdapter(fastCharacterRyAdapter);
        img_pause=view.findViewById(R.id.img_pause);
        donutProgress = view.findViewById(R.id.donut_progress);
        donutProgress.setProgress(0);
        donutProgress.setMax((haiSlowTrain?TOTALTIME_SLOWTRAIN:TOTALTIME_FASTTRAIN));
        rl_recorder = view.findViewById(R.id.rl_recorder);
        tv_syllableSlow = view.findViewById(R.id.tv_syllable_slow);
        tv_syllableFast = view.findViewById(R.id.tv_syllable_fast);
        tv_syllableSlow.setText(UniCodeUtils.convertToChinese(wordArticulation.getUS_phonetic()));
        tv_syllableFast.setText(UniCodeUtils.convertToChinese(wordArticulation.getUS_phonetic()));
//        ImageView img_recorder=view.findViewById(R.id.img_recorder);
//        AnimationDrawable animation = (AnimationDrawable)img_recorder.getDrawable();
//        animation.start();

        try{
            Typeface typeFace = Typeface.createFromAsset(getContext().getAssets(), "klg_droid_sans_bold.ttf");
            tv_syllableSlow.setTypeface(typeFace);
            tv_syllableFast.setTypeface(typeFace);
        }catch (Exception e){
        }
        rl_countTime = view.findViewById(R.id.rl_count_time);
        countTimeView = view.findViewById(R.id.counttime_view);
        img_completeLogo = view.findViewById(R.id.img_complete_logo);
        tv_alert = view.findViewById(R.id.tv_spell_memory_write_alert);
        tv_giveUpTrain = view.findViewById(R.id.tv_pass_train);
        tv_giveUpTrain.setOnClickListener(this);
        resetReadingTrainStyle();
        boolean isAlert = getArguments().getBoolean(BasicTrainBaseFragment.KEY_IS_ALERT);
        view.findViewById(R.id.img_alert_slow).setVisibility(isAlert?View.VISIBLE:View.GONE);
        if(isAlert&&haiSlowTrain){
            img_arrorSlow.setImageResource(R.mipmap.klg_more_speech_step2);
        }
        if(isAlert&&!haiSlowTrain){
            ImageView img_alert=view.findViewById(R.id.img_alert_slow);
            img_alert.setImageResource(R.mipmap.klg_more_speech_word);
        }
    }

    /**
     * 数据组装
     */
    private void splitData(){
        fastCharacterBeans=new ArrayList<>();
        slowCharacterBeans=new ArrayList<>();
        slowTimeBeans=new ArrayList<>();
        //快速环节数据组装
        for (int i = 0; i < wordArticulation.getKlgName().length(); i++) {
            SpellCharacterBean spellCharacterBean=new SpellCharacterBean();
            spellCharacterBean.setCharacter(wordArticulation.getKlgName().substring(i,i+1));
            fastCharacterBeans.add(spellCharacterBean);
        }
        //慢速环节数据组装
        String[] split =  wordArticulation.getSyllable().split("·|-");
        int index=-1;
        for (int i = 0; i <split.length; i++) {
            int length=split[i].length();
            index+=length;
            int time=TOTALTIME_SLOWTRAIN*(i+1)/split.length;
            SpellCharacterBean spellCharacterBean=new SpellCharacterBean();
            spellCharacterBean.setCharacter(split[i]);
            spellCharacterBean.setEndIndex(index);
            spellCharacterBean.setTimeLength(time);
            slowTimeBeans.add(spellCharacterBean);
            index+=1;
        }
        for (int i = 0; i < wordArticulation.getSyllable().length(); i++) {
            SpellCharacterBean slowCharacterBean=new SpellCharacterBean();
            slowCharacterBean.setCharacter(wordArticulation.getSyllable().substring(i,i+1));
            slowCharacterBeans.add(slowCharacterBean);
        }
        haiSlowTrain=split.length>1;
    }

    /**
     * 切换训练样式
     */
    private void changeReadingTrainState(){
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) tv_syllableSlow.getLayoutParams();
        if(pronounceState== PronounceState.SLOWDREAD){

            rl_fast.setBackground(null);
            rl_slow.setBackgroundResource(R.mipmap.klg_icon_articulate_bg);
            slowCharacterAdapter.setTrainMode(1,false);
            fastCharacterRyAdapter.setTrainModel(false);
            fastCharacterRyAdapter.changeRepeat(-1);
            img_arrorSlow.setImageResource(R.mipmap.klg_icon_arror_down_gray);
            tv_syllableSlow.setTextColor(Color.WHITE);
            tv_syllableFast.setTextColor(Color.parseColor("#b9b9b9"));
            layoutParams.topMargin= KlgToolUtils.dip2px(getContext(),5);
            tv_syllableSlow.setLayoutParams(layoutParams);
            donutProgress.setProgress(0);
        }else{
//            rl_slow.setBackground(null);
            rl_slow.setBackgroundResource(R.mipmap.klg_icon_articulate_tansparent_bg);
            rl_fast.setBackgroundResource(R.mipmap.klg_icon_articulate_bg);
            fastCharacterRyAdapter.setTrainModel(true);
            slowCharacterAdapter.setTrainMode(2,false);
            img_arrorSlow.setImageResource(R.mipmap.klg_icon_arror_down_bule);
            tv_syllableSlow.setTextColor(Color.parseColor("#b9b9b9"));
            tv_syllableFast.setTextColor(Color.WHITE);
            layoutParams.topMargin= KlgToolUtils.dip2px(getContext(),2);
            tv_syllableSlow.setLayoutParams(layoutParams);
        }
    }

    /**
     * 重置发音朗读训练样式
     */
    private void resetReadingTrainStyle(){
        if(rl_recorder==null){
            return;
        }
        img_pause.setVisibility(View.GONE);
        rl_recorder.setVisibility(View.GONE);
        donutProgress.setVisibility(View.VISIBLE);
        donutProgress.setProgress(0);
        donutProgress.setMax((haiSlowTrain?TOTALTIME_SLOWTRAIN:TOTALTIME_FASTTRAIN));
        countTimeView.setVisibility(View.VISIBLE);
        img_completeLogo.setVisibility(View.GONE);
        if(!haiSlowTrain){
            rl_slow.setVisibility(View.GONE);
            img_arrorSlow.setVisibility(View.GONE);
            pronounceState= PronounceState.FASTREAD;
            fastCharacterRyAdapter.changeRepeat(-1);
        }else{
            pronounceState= PronounceState.SLOWDREAD;
            slowCharacterAdapter.changeRepeat(-1);
        }
        changeReadingTrainState();
        rl_countTime.setVisibility(View.GONE);
        tv_alert.setText(R.string.klg_start_phonetic_train_alert);
        tv_giveUpTrain.setVisibility(View.INVISIBLE);
    }

    /**
     * 重置快速朗读样式
     */
    private void resetFastReadingTrainStyle(){
        changeReadingTrainState();
        if(!haiSlowTrain){
            rl_slow.setVisibility(View.GONE);
            img_arrorSlow.setVisibility(View.GONE);
            pronounceState= PronounceState.FASTREAD;
        }else{
            pronounceState= PronounceState.SLOWDREAD;
            slowCharacterAdapter.changeRepeat(-1);
        }
    }


    /**
     * 滴一声后开始训练
     */
    protected void startSubModelTrain(){
        if(rl_recorder==null){
           return;
        }
        rl_recorder.setVisibility(View.VISIBLE);
        if(pronounceState==PronounceState.SLOWDREAD){
            slowTrainIndex=0;
            slowCharacterAdapter.changeRepeat(slowTimeBeans.get(slowTrainIndex).getEndIndex());
            slowTrainIndex++;
            donutProgress.setMax((haiSlowTrain?TOTALTIME_SLOWTRAIN:TOTALTIME_FASTTRAIN));
        }else if(pronounceState==PronounceState.FASTREAD){
            fastCharacterRyAdapter.setTrainModel(true);
            fastCharacterRyAdapter.changeRepeat(1);
            donutProgress.setVisibility(View.VISIBLE);
            rl_recorder.setVisibility(View.VISIBLE);
            donutProgress.setMax(TOTALTIME_FASTTRAIN);
        }
    }

    /**
     * 更新进度
     * @param recordProgress
     */
    protected void upDateRecordAnswerProgress(int recordProgress){
        if(!haiSlowTrain){
            if(donutProgress!=null){
                donutProgress.setProgress(recordProgress);
            }
            if(recordProgress>=TOTALTIME_FASTTRAIN){
                Log.e("aaaa","快速朗读 结束作答，结束打分");
                stopRecordSpeechEvaluation();
            }
            return;
        }
        if(pronounceState== PronounceState.FASTREAD){
            recordProgress-=TOTALTIME_SLOWTRAIN;
        }
        if(donutProgress!=null){
            donutProgress.setProgress(recordProgress);
        }
        if(pronounceState== PronounceState.SLOWDREAD){//慢速朗读更新
            if(recordProgress>TOTALTIME_SLOWTRAIN){
                Log.e("aaaa","慢速朗读 结束作答，结束打分");
                stopRecordSpeechEvaluation();
            }else{
                if(slowTrainIndex>0&&slowTrainIndex<slowTimeBeans.size()&&recordProgress>slowTimeBeans.get(slowTrainIndex-1).getTimeLength()){
                    Log.e("aaaaa","慢速朗读...."+slowTimeBeans.get(slowTrainIndex).getEndIndex());
                    slowCharacterAdapter.changeRepeat(slowTimeBeans.get(slowTrainIndex).getEndIndex());
                    scrollIndex(rv_slow,slowTimeBeans.get(slowTrainIndex).getEndIndex(),wordArticulation.getSyllable().length(),true);
                    slowTrainIndex++;
                }
            }
        }else{//快速朗读进度更新
//            if(recordProgress>=TOTALTIME_FASTTRAIN+(haiSlowTrain?TOTALTIME_SLOWTRAIN:0)){
            if(recordProgress>=TOTALTIME_FASTTRAIN){
                Log.e("aaaa","快速朗读 结束作答，结束打分");
                stopRecordSpeechEvaluation();
            }
        }
    }

    /**
     * 评测正常
     * @param grade
     * @param url
     * @param skegnResult
     */
    protected void onSuccessSpeechEvaluation(int grade, String url, LgEvaluateObj skegnResult){
        if(pronounceState== PronounceState.SLOWDREAD){
            pronounceState= PronounceState.FASTREAD;
            changeReadingTrainState();
            startDripMusic();
            slowReadScore=grade;
            slowRecordUrl=url;

        }else{
            pronounceState= haiSlowTrain?PronounceState.SLOWDREAD:PronounceState.FASTREAD;
            Log.e("aaaa","快速朗读评分结束...");
            fastReadScore=grade;
            fastRecordUrl=url;
            if(haiSlowTrain){
                totalScore = (int)(slowReadScore*0.2f+fastReadScore*0.8f);
            }else{
                totalScore = fastReadScore;
            }
            isQuality=totalScore>= KlgConstant.SCORE_QUALITY;
            upDateTrainResult(isQuality,totalScore);
            playResultMusic(isQuality);
            List<String> readingRecordUrlList=new ArrayList<>();
            if(haiSlowTrain&& !TextUtils.isEmpty(slowRecordUrl)){
                readingRecordUrlList.add(slowRecordUrl);
            }
            readingRecordUrlList.add(fastRecordUrl);
//            resetReadingTrainStyle();
            showReadingTrainResult();
            startSecondTimer();
//            enterPronounceResultActivity(totalScore,readingRecordUrlList,getString(R.string.klg_result_reading));
        }
    }

    /**
     * 展示作答结果
     */
    private void showReadingTrainResult() {
        if(rl_recorder==null){
            return;
        }
        rl_recorder.setVisibility(View.GONE);
        if(isQuality){
            tv_alert.setText(getArguments().getBoolean(BasicTrainBaseFragment.KEY_ISMORE_ENTER)?R.string.klg_result_exit_train_for_pronounce:R.string.klg_result_pronounce_reading_correct);
        }else{
            tv_alert.setText(R.string.klg_result_pronounce_reading_error);
        }
        convertView.findViewById(R.id.rl_count_time).setVisibility(View.VISIBLE);
        countTimeView.setAngle(0,2000);
        tv_giveUpTrain.setVisibility(isQuality?View.GONE:View.VISIBLE);
        img_completeLogo.setVisibility(isQuality?View.VISIBLE:View.GONE);
        countTimeView.setVisibility(isQuality?View.GONE:View.VISIBLE);
    }

    /**
     *训练暂停
     */
    protected void pauseTrain(boolean isReset){
        Log.e("aaaa","朗读发音训练暂停，pauseTrain");
        if(isReset){
            resetReadingTrainStyle();
        }else {
            if(img_pause!=null){
                img_pause.setVisibility(View.VISIBLE);
                donutProgress.setVisibility(View.INVISIBLE);
                rl_countTime.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 继续发音训练
     */
    protected void continueTrain(){
        if(pronounceState==PronounceState.SLOWDREAD){
            resetReadingTrainStyle();
        }else{
            if(img_pause!=null){
                fastCharacterRyAdapter.changeRepeat(-1);
                img_pause.setVisibility(View.GONE);
                rl_recorder.setVisibility(View.GONE);
                donutProgress.setProgress(0);
            }
        }
        startDripMusic();
    }

    protected int getStratTrainProgress(){
        return haiSlowTrain?TOTALTIME_SLOWTRAIN:0;
    }

    /**
     * 3，2，1s倒计时进度更新
     * @param progress
     * @param totalProgress
     */
    protected void updateCountTime(int progress,int totalProgress){
        if(rl_countTime!=null){
            rl_countTime.setVisibility(progress>=totalProgress?View.GONE:View.VISIBLE);
            countTimeView.setAngle(progress,totalProgress);
        }
    }

    /**
     * 作答结束2s倒计时
     * @param progress
     * @param totalProgress
     */
    protected void updateResultCountTime(int progress,int totalProgress){
        if(countTimeView==null){
            return;
        }
        countTimeView.setAngle(progress,totalProgress);
        if(progress==totalProgress){
            Log.e("aaaa","暂停。。。。"+isQuality);
            if(!isQuality){//不合格 进入跟读训练界面
                resetReadingTrainStyle();
                enterPronunceRepeatNextTrain(totalScore,null);
            }else{
                resetReadingTrainStyle();
                enterPronunceRepeatNextTrain(totalScore,null);
            }
        }
    }

}
